#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define SIZE 50

struct node
{
    char name[SIZE];
    float grades[SIZE];
    struct node *next;
};
typedef struct node Tnode;

struct list
{
    Tnode *first;
    Tnode *last;
};
typedef struct list LIST;

LIST L;

void add_to_right(float, char *, int, LIST *);
void iterate(LIST L, int);
int check(LIST L, char *, int, float);

float grade = 0.0;
int main(int argc, char *argv[])
{
    FILE *fp;
    int c, k, comma, i;
    char buffer[SIZE];
    

	for (i = 1; i <= argc; ++i)
    {
		fp = fopen(argv[i], "r+");

		k = -1;
		comma = 0;
		while ((c = fgetc(fp)) != EOF)
		{
			while (c != '\n')
			{
				++k;
				buffer[k] = c;
				c = fgetc(fp);

				if (c == ',')
					++comma;

				if (comma == 2)
				{
					fscanf(fp, "%f", &grade);
					comma = 0;
				}
			}
			buffer[k + 1] = '\0';
			if (check(L, buffer, i, grade) == 0)
				add_to_right(grade, buffer, i, &L);
			k = -1;
		}
	}

    iterate(L, argc);

    fclose(fp);

    return 0;
}

void add_to_right(float gra, char *nam, int pos, LIST *L)
{
	int i;
    Tnode *tmp;
    tmp = (Tnode *)malloc(sizeof(Tnode));

	for (i = 0; i <= SIZE; ++i)
		tmp -> grades[i] = 0.0;
	
    strcpy(tmp -> name, nam);
    tmp -> grades[pos] = gra;
    tmp -> next = NULL;

    if(L -> last != NULL)
    {
        L -> last -> next = tmp;
        L -> last = tmp;
    }

    else
        L -> first = L -> last = tmp;
}

void iterate(LIST L, int no)
{
    FILE *fp1;
	int i;
    fp1 = fopen("final.csv", "r+");
    Tnode *tmp = L.first;

    if(tmp == NULL)
        printf("list is empty.");
    else
        for(; tmp != NULL; tmp = tmp -> next)
        {
            fprintf(fp1, "%s ", tmp -> name);
            for (i = 1; i < no; ++i)
				fprintf(fp1, "%.2f ", tmp -> grades[i]);
			fprintf(fp1, "\n");
        }
    fclose(fp1);
}

int check(LIST L, char *buf, int pos, float x)
{
	int ok = 0;
	Tnode *tmp = L.first;

    
    for(; tmp != NULL; tmp = tmp -> next)
		if(strcmp(tmp -> name, buf) == 0)
		{	
			ok = 1;
			tmp -> grades[pos] = x;				
		}
    return ok;
}